import type { Ref } from 'vue';
import { onMounted, onUnmounted, unref } from 'vue';
import echarts from './library';
// import type { EChartsOption } from 'echarts'
import { SVGRenderer, CanvasRenderer } from 'echarts/renderers';
import { RenderType, ThemeType } from './echarts-types';
export const useECharts = (
  elparams: Ref<HTMLDivElement> | HTMLDivElement,
  autoUpdateSize: boolean = false,
  render: RenderType.SVGRenderer = RenderType.CanvasRenderer,
  theme = ThemeType.Default
) => {
  // 渲染模式
  echarts.use(CanvasRenderer);
  // echarts.use(render == RenderType.SVGRenderer ? SVGRenderer : CanvasRenderer);
  // echats实例
  let echartsInstance: echarts.ECharts | null = null;
  // 初始化实例
  const initCharts = () => {
    const el = unref(elparams);
    if (!el) return;
    echartsInstance = echarts.init(el, theme);
  };
  // 配置
  const setOptions = (option: any) => {
    showLoading();
    if (!echartsInstance) initCharts();
    if (!echartsInstance) return;
    echartsInstance.setOption(option, {notMerge: true});
    hideLoading();

    window.addEventListener('resize', onResize);
    watchEl();
  };
  const showLoading = () => {
    if (!echartsInstance) initCharts();
    echartsInstance?.showLoading();
  };
  const hideLoading = () => {
    if (!echartsInstance) initCharts();
    echartsInstance?.hideLoading();
  };
  const getInstance = () => {
    if (!echartsInstance) initCharts();
    return echartsInstance;
  };
  const onResize = () => {
    echartsInstance?.resize();
  };
  const watchEl = () => {
    const resizeObserve = new ResizeObserver(() => onResize());
    resizeObserve.observe(unref(elparams));
  };
  onUnmounted(() => {
    window.removeEventListener('resize', onResize);
  });
  return {
    setOptions,
    getInstance,
  };
};
